import React, {PureComponent} from 'react';
import routes from './routes';
import {Table, Card} from 'antd';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import {
    PAGE,
    TABLE,
    DATETIME_FORMAT,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    FIXED_COLUMN_WIDTH
} from '../constants';
import {PERMISSION} from './constants';
import {conventSorter, hasPermissions} from './utils';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {formatDateTime, conventEnumValueToString} from '../utils';
import {saleShipmentStatus, saleOrderTransportType, declarePlace, declareType} from '../Enum';
export class TablePanel extends PureComponent {
    state = {
        loading: false
    };
    handleAbandon = id => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };
    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({...conventSorter(sorter),
                pageIndex: PAGE.index});
    };
    render() {
        const {formatMessage} = this.props.intl;
        const {pageIndex, pageSize, total, permissions} = this.props;
        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.code',
                defaultMessage: '发运单号'
            }),
            dataIndex: 'code',
            sorter: true,
            render: (text, record) => (
                <Link key="detail" to={routes.detail.format(record.id)}>
                    {text}
                </Link>
            )
        }, {
            title: formatMessage({
                id: 'tablePanel.column.dealerCode',
                defaultMessage: '总代编号'
            }),
            dataIndex: 'dealerCode',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.dealerName',
                defaultMessage: '总代名称'
            }),
            dataIndex: 'dealerName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.partShipmentStatus',
                defaultMessage: '状态'
            }),
            dataIndex: 'partShipmentStatus',
            sorter: true,
            render: text => conventEnumValueToString(saleShipmentStatus, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.transportType',
                defaultMessage: '运输方式'
            }),
            dataIndex: 'transportType',
            sorter: true,
            render: text => conventEnumValueToString(saleOrderTransportType, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.origin',
                defaultMessage: '起运地'
            }),
            dataIndex: 'origin',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.destination',
                defaultMessage: '目的地'
            }),
            dataIndex: 'destination',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.expectShipmentDate',
                defaultMessage: '预计发运日期'
            }),
            dataIndex: 'expectShipmentDate',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.actualShipmentDate',
                defaultMessage: '实际发运日期'
            }),
            dataIndex: 'actualShipmentDate',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.expectDepartedDate',
                defaultMessage: '预计离港日期'
            }),
            dataIndex: 'expectDepartedDate',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.expectArrivalDate',
                defaultMessage: '预计到港日期'
            }),
            dataIndex: 'expectArrivalDate',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.expectShipmentDay',
                defaultMessage: '预计发运天数'
            }),
            dataIndex: 'expectShipmentDay',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.actualDepartedDate',
                defaultMessage: '实际离港日期'
            }),
            dataIndex: 'actualDepartedDate',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.actualArrivalDate',
                defaultMessage: '实际到港日期'
            }),
            dataIndex: 'actualArrivalDate',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.actualShipmentDay',
                defaultMessage: '实际发运天数'
            }),
            dataIndex: 'actualShipmentDay',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.declarePlace',
                defaultMessage: '报关地点'
            }),
            dataIndex: 'declarePlace',
            render: text => conventEnumValueToString(declarePlace, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.declareType',
                defaultMessage: '报关类型'
            }),
            dataIndex: 'declareType',
            render: text => conventEnumValueToString(declareType, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.createTime',
                defaultMessage: '创建时间'
            }),
            dataIndex: 'createTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.action',
                defaultMessage: '操作'
            }),
            dataIndex: 'action',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [
                    {
                        id: PERMISSION.update,
                        children: (
                            <Link key="update" to={routes.update.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.update',
                                    defaultMessage: '编辑'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                    }, {
                        id: PERMISSION.abandon,
                        children: ref =>
                            <WrappedPopconfirm
                                id={r.id}
                                key="abandon"
                                title={formatMessage({
                                    id: 'tablePanel.popconfirm.message',
                                    defaultMessage: '是否继续?'
                                })}
                                onVisibleChange={ref.setMenuVisible}
                                onConfirm={this.handleAbandon}>
                                <a key="abandon">
                                    {formatMessage({
                                        id: 'tablePanel.operation.abandon',
                                        defaultMessage: '作废'
                                    })}
                                </a>
                            </WrappedPopconfirm>,
                        hidden: !(hasPermissions(permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                    }, {
                        id: PERMISSION.signned,
                        children: (
                            <Link key="signned" to={routes.signned.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.signned',
                                    defaultMessage: '签收'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.signned) && hasPermissions(r.options, PERMISSION.signned))
                    }, {
                        id: PERMISSION.dateSupplement,
                        children: (
                            <Link key="dateSupplement" to={routes.dateSupplement.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.dateSupplement',
                                    defaultMessage: '日期补录'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.dateSupplement) && hasPermissions(r.options, PERMISSION.dateSupplement))
                    }];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        }];
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <Card>
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE}/>
            </Card>
        );
    }
}

TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onClickAbandon: PropTypes.func.isRequired,
    onPageIndexChange: PropTypes.func.isRequired,
    onPageSizeChange: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
};
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch, onClickAbandon, querySearch} from './actions';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    permissions: getPermissions(state)
});

const mapDispatchToProps = dispatch => ({
    onPageSizeChange: (pageIndex, pageSize) =>
        dispatch(
            tableSearch({
                pageIndex: PAGE.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    onChangeSort: option => dispatch(tableSearch(option)),
    onClickAbandon: id =>
        dispatch(onClickAbandon(id)).then(success => {
            if(success) dispatch(querySearch());
            return success;
        }),
});
import {connect} from 'react-redux';
import {injectIntl} from './intl';
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
